﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Xpedite.Localization;
using Xpedite.Resources.Builders;

/* Copyright (c) 2010 CBaxter
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 * IN THE SOFTWARE. 
 */

namespace Xpedite.Resources.Definitions
{
  internal abstract class DefinitionBase : IResourceDefinition
  {
    private readonly List<INamedValue<IResourceContainer>> _references = new List<INamedValue<IResourceContainer>>();
    private readonly HashSet<String> _referencedNames = new HashSet<String>();
    private readonly IResourceBuilderFactory _builderFactory;
    private readonly IResourceUrlGenerator _urlGenerator;
    private readonly IResourceCache _resourceCache;
    private readonly INamingRule _namingRule;
    private readonly String _referenceName;

    public IEnumerable<IResourceContainer> Resources { get { return _references.Select(item => item.Value); } }
    public IEnumerable<INamedValue<IResourceContainer>> References { get { return _references; } }
    public String ReferenceName { get { return _referenceName; } }
    public abstract ResourceType ResourceType { get; }

    protected DefinitionBase(DefinitionArgs args, String referenceName, INamingRule namingRule)
    {
      Verify.NotNull(args, "args");
      Verify.NotNull(namingRule, "namingRule");

      if (!namingRule.IsSatisfiedBy(referenceName))
        throw new XpediteException(String.Format(ExceptionMessages.InvalidCompositeResourceReferenceName, referenceName, ResourceType));

      _builderFactory = args.BuilderFactory;
      _resourceCache = args.ResourceCache;
      _urlGenerator = args.UrlGenerator;
      _referenceName = referenceName;
      _namingRule = namingRule;
    }

    public void ReferenceResources(IEnumerable<INamedValue<IResourceUrl>> namedResourceUrls)
    {
      foreach (var namedResourceUrl in namedResourceUrls)
        ReferenceResource(namedResourceUrl);
    }

    public void ReferenceResource(INamedValue<IResourceUrl> namedResourceUrl)
    {
      if (_referencedNames.Contains(namedResourceUrl.Name))
        throw new XpediteException(String.Format(ExceptionMessages.DuplicateResourceReferenceName, namedResourceUrl.Name, ReferenceName));

      if (!_namingRule.IsSatisfiedBy(namedResourceUrl.Name))
        throw new XpediteException(String.Format(ExceptionMessages.InvalidResourceReferenceName, namedResourceUrl.Name, ReferenceName, ResourceType));

      INamedValue<IResourceContainer> namedResourceContainer = NamedValue.Create(namedResourceUrl.Name, GetOrCreateResource(namedResourceUrl.Value));

      _referencedNames.Add(namedResourceContainer.Name);
      _references.Add(namedResourceContainer);
    }

    private IResourceContainer GetOrCreateResource(IResourceUrl resourceUrl)
    {
      Func<IResourceContainer> resourceFactory = () => _builderFactory.Create(ResourceType, resourceUrl).Build();

      return resourceUrl.IsLocal
               ? _resourceCache.GetOrCreateWithFileDependency(resourceUrl, resourceFactory, resourceUrl.PhysicalPath)
               : _resourceCache.GetOrCreateWithNoDependency(resourceUrl, resourceFactory);
    }

    public IResourceContainer GetResource(String referenceName)
    {
      if (!_referencedNames.Contains(referenceName))
        throw new XpediteException(String.Format(ExceptionMessages.UnknownResourceReferenceName, referenceName, ReferenceName));

      return _references.First(reference => String.CompareOrdinal(reference.Name, referenceName) == 0).Value;
    }

    public abstract void EmitResource(HtmlTextWriter writer);
  }
}
